"""
MySQL 数据库工具模块
提供 MySQL 数据库连接和操作功能
"""
import os
import pymysql
from typing import Optional

from configs.basic_config import MYSQL_DATABASE_URL


def get_mysql_connection():
    """
    获取 MySQL 数据库连接
    
    Returns:
        pymysql.Connection: MySQL 数据库连接对象
    """
    # 解析连接字符串获取连接参数
    # 格式: mysql+pymysql://user:password@host:port/database
    parts = MYSQL_DATABASE_URL.split("://")[1]
    user_pass, host_port_db = parts.split("@")
    user, password = user_pass.split(":")
    host_port, database = host_port_db.split("/")
    host, port = host_port.split(":")
    
    # 创建连接
    connection = pymysql.connect(
        host=host,
        port=int(port),
        user=user,
        password=password,
        database=database,
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    
    return connection

def test_mysql_connection():
    """
    测试 MySQL 数据库连接
    
    Returns:
        bool: 连接是否成功
    """
    connection = None
    try:
        connection = get_mysql_connection()
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            return result is not None
    except Exception as e:
        print(f"数据库连接失败: {e}")
        return False
    finally:
        if connection:
            try:
                connection.close()
            except:
                pass

def execute_query(query, params=None):
    """
    执行查询语句
    
    Args:
        query (str): SQL 查询语句
        params (tuple, optional): 查询参数
        
    Returns:
        list: 查询结果
    """
    connection = get_mysql_connection()
    try:
        with connection.cursor() as cursor:
            cursor.execute(query, params)
            result = cursor.fetchall()
            return result
    finally:
        connection.close()

def execute_update(query, params=None):
    """
    执行更新语句
    
    Args:
        query (str): SQL 更新语句
        params (tuple, optional): 更新参数
        
    Returns:
        int: 受影响的行数
    """
    connection = get_mysql_connection()
    try:
        with connection.cursor() as cursor:
            affected_rows = cursor.execute(query, params)
            connection.commit()
            return affected_rows
    finally:
        connection.close()